package com.dykj.fireFighting.web.app;

import com.dykj.fireFighting.api.base.enterprise.entity.Enterprise;
import com.dykj.fireFighting.api.base.enterprise.service.IEnterpriseService;
import com.dykj.fireFighting.api.base.file.service.OfficeService;
import com.dykj.fireFighting.api.fire.contractMessage.service.IContractMessageService;
import com.dykj.fireFighting.api.fire.contractMessage.vo.ContractMessagesVo;
import com.dykj.fireFighting.api.fire.maintenanceplan.dto.RoutineMaintenanceDto;
import com.dykj.fireFighting.api.fire.maintenanceplan.entity.RoutineMaintenance;
import com.dykj.fireFighting.api.fire.maintenanceplan.entity.RoutineMaintenanceRecord;
import com.dykj.fireFighting.api.fire.maintenanceplan.service.IRoutineMaintenanceRecordService;
import com.dykj.fireFighting.api.fire.maintenanceplan.service.IRoutineMaintenanceService;
import com.dykj.fireFighting.api.fire.maintenanceplan.vo.RoutineMaintenanceVo;
import com.dykj.fireFighting.api.socialUnit.devicemanger.dto.DeviceInfoDto;
import com.dykj.fireFighting.api.socialUnit.devicemanger.entity.DeviceInfo;
import com.dykj.fireFighting.api.socialUnit.devicemanger.service.IDeviceInfoService;
import com.dykj.fireFighting.api.socialUnit.xfxg.entity.FireGroup;
import com.dykj.fireFighting.api.socialUnit.xfxg.service.IFireGroupService;
import com.dykj.fireFighting.api.socialUnit.xfxg.vo.FireGroupVo;
import com.dykj.fireFighting.common.core.annotation.AutoLog;
import com.dykj.fireFighting.common.core.api.CommonResult;
import com.dykj.fireFighting.common.core.utils.UUIDUtils;
import com.dykj.fireFighting.common.core.vo.LoginUserVo;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.web.base.shiro.ShiroUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 例行维保记录接口
 *
 * @Author fgc
 * @Date 2021-07-28 16:30:03
 */
@Slf4j
@Api(value = "app例行维保记录接口", tags = {"app例行维保记录接口"})
@RestController
@RequestMapping("app/routineMaintenance")
public class AppRoutineMaintenanceController {

    @DubboReference
    private IRoutineMaintenanceService routineMaintenanceService;
    @DubboReference
    private IRoutineMaintenanceRecordService routineMaintenanceRecordService;
    @DubboReference
    private IEnterpriseService enterpriseService;
    @DubboReference(check = false)
    private OfficeService officeService;
    @DubboReference
    private IDeviceInfoService deviceInfoService;
    @DubboReference
    private IFireGroupService fireGroupService;
    @DubboReference
    private IContractMessageService iContractMessageService;

    /**
     * 消防群组查询设备信息
     *
     * @return
     */
    /*@AutoLog(value = "消防群组查询设备信息")*/
    @ApiOperation(value = "消防群组查询设备信息", notes = "消防群组查询设备信息")
    @GetMapping("/deviceList")
    /*  @RequiresPermissions("app/deviceList/list")*/
    public CommonResult treeGrid(@RequestParam("groupId") String groupId) {
        FireGroupVo deviceByGroupId = deviceInfoService.getDeviceByGroupId(groupId);
        return CommonResult.success(deviceByGroupId);
    }

    /**
     * 例行维保记录列表
     *
     * @return
     */
    /*@AutoLog(value = "例行维保记录-分页列表查询")*/
    @ApiOperation(value = "例行维保记录分页列表", notes = "例行维保记录分页列表")
    @GetMapping("/list")
    // @RequiresPermissions("routineMaintenance/list")
    public CommonResult<PageVo<RoutineMaintenanceVo>> treeGrid(RoutineMaintenanceDto routineMaintenanceDto) {

        routineMaintenanceDto.setMaintenanceDept(ShiroUtil.getUser().getEnterpriseId().toString());
        PageVo<RoutineMaintenanceVo> page = routineMaintenanceService.queryList(routineMaintenanceDto);
        return CommonResult.success(page);
    }

    /**
     * 获取例行维保记录信息
     */
    @AutoLog(value = "例行维保记录-获取例行维保记录信息")
    @ApiOperation(value = "获取例行维保记录信息", notes = "获取例行维保记录信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "主键ID", dataType = "String", required = true)
    @GetMapping("/info/{id}")
    /*@RequiresPermissions("routineMaintenance/info")*/
    public CommonResult<RoutineMaintenance> info(@PathVariable("id") String id) {
        RoutineMaintenance routineMaintenance = routineMaintenanceService.getById(id);
        return CommonResult.success(routineMaintenance);
    }

    /**
     * 保存例行维保记录信息
     */
    @AutoLog(value = "例行维保记录-保存例行维保记录信息")
    @ApiOperation(value = "保存例行维保记录信息", notes = "保存例行维保记录信息")
    @PostMapping("/save")
    @Transactional
    /*  @RequiresPermissions("routineMaintenance/save")*/
    public CommonResult save(@Valid @RequestBody RoutineMaintenance routineMaintenance) {
        try {
            //保存例行维保报告
            LoginUserVo user = ShiroUtil.getUser();
            routineMaintenance.setId(UUIDUtils.get32UUID());
            routineMaintenance.setCreateDate(new Date());
            routineMaintenance.setCreateBy(user.getId().toString());
            routineMaintenance.setMaintenanceDept(user.getEnterpriseId().toString());
            routineMaintenance.setMaintenanceDeptName(user.getEnterpriseName());
            //获取扫描的nfc第一个群组
            String fireGroupId = routineMaintenance.getRoutineMaintenanceRecords().get(0).getFireGroupId();
            System.out.println("群组id----------------"+fireGroupId);
            //获取群组所在的社会单位信息
            FireGroup fireGroup=fireGroupService.getById(fireGroupId);
            if(null == fireGroup){
                return CommonResult.failed("添加失败，群组不存在");
            }
            Enterprise e = enterpriseService.getById(fireGroup.getUnitId());
            routineMaintenance.setSociologyDept(e.getId().toString());
            routineMaintenance.setSociologyDeptName(e.getEnterpriseName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            routineMaintenance.setMaintenanceDate(sdf.format(routineMaintenance.getCreateDate()));
            //获取双方项目负责人
            ContractMessagesVo byUnitMaintenance = iContractMessageService.getByUnitMaintenance(routineMaintenance.getSociologyDept(), routineMaintenance.getMaintenanceDept());
            if(null == byUnitMaintenance){
                return CommonResult.failed("添加失败，维保合同不存在或已到期");
            }
            routineMaintenance.setSociologyProjectDutyMan(byUnitMaintenance.getPartyA());
            routineMaintenance.setMaintenanceProjectDutyMan(byUnitMaintenance.getPartyB());
            for (RoutineMaintenanceRecord routineMaintenanceRecord : routineMaintenance.getRoutineMaintenanceRecords()) {
                routineMaintenanceRecord.setId(UUIDUtils.get32UUID());
                routineMaintenanceRecord.setRoutineMaintenanceId(routineMaintenance.getId());
                routineMaintenanceRecord.setCreateTime(new Date());
                routineMaintenanceRecord.setCreateBy(user.getId().toString());
                routineMaintenanceRecord.setMaintenanceStandard(fireGroupService.getById(routineMaintenanceRecord.getFireGroupId()).getRemark());
            }
            //生成报告文件并将文件id存入维保报告数据库中
            Map<String, Object> map = new HashMap<>();
            map.put("routineMaintenance", routineMaintenance);
            String ids = officeService.excelToPdfSave(map, "RoutineMaintenanceRecord.xlsx", routineMaintenance.getSociologyDeptName() + "例行维保报告.pdf");
            if (StringUtils.isNotBlank(ids)){
                routineMaintenance.setFileId(ids);
                boolean save = routineMaintenanceService.save(routineMaintenance);
                if (save) {
                    //保存例行维保记录数据
                    routineMaintenanceRecordService.saveBatch(routineMaintenance.getRoutineMaintenanceRecords(),routineMaintenance.getRoutineMaintenanceRecords().size()+100);

                /*RoutineMaintenance update = new RoutineMaintenance();
                update.setFileId(ids);
                update.setId(routineMaintenance.getId());
                routineMaintenanceService.updateById(update);*/
                }
                return CommonResult.success("添加成功");
            }
            return CommonResult.failed("添加失败，请联系管理员");
        } catch (Exception e) {
            log.error(e.getMessage());
            return CommonResult.failed("添加失败，请联系管理员");
        }
    }

    /**
     * 例行维保数量
     *
     * @return
     */
    /*@AutoLog(value = "例行维保记录-分页列表查询")*/
    @ApiOperation(value = "例行维保数量", notes = "例行维保数量")
    @GetMapping("/num")
    // @RequiresPermissions("routineMaintenance/list")
    public CommonResult<Integer> getNum(String type) {
        Map<String, String> params = new HashMap<>();
        if (StringUtils.isNotBlank(type)) {
            params.put("type", type);
        }
        params.put("wbId", ShiroUtil.getUser().getEnterpriseId().toString());
        int maintenanceNum = routineMaintenanceService.getMaintenanceNum(params);
        return CommonResult.success(maintenanceNum);
    }

    /**
     * 例行维保 维保机构当月评价得分详情
     *
     * @param routineMaintenanceDto
     * @return
     */
    @AutoLog(value = "例行维保 维保机构当月评价得分详情")
    @ApiOperation(value = "例行维保 维保机构当月评价得分详情", notes = "例行维保 维保机构当月评价得分详情")
    @GetMapping("/queryRoutineMaintenanceEvaluationInfoList")
    public CommonResult<List<RoutineMaintenanceVo>> queryRoutineMaintenanceEvaluationInfoList(RoutineMaintenanceDto routineMaintenanceDto) {
        String unitId = ShiroUtil.getUser().getEnterpriseId().toString();
        routineMaintenanceDto.setMaintenanceDept(unitId);
        List<RoutineMaintenanceVo> routineMaintenanceVoList = routineMaintenanceService.queryRoutineMaintenanceEvaluationInfoList(routineMaintenanceDto);
        return CommonResult.success(routineMaintenanceVoList);
    }
}
